<template>
  <div>
    <div class="crud-opts">
      <el-button
        v-loading="loading"
        v-if="editable"
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-cpu"
        @click="doRunMrp">MRP运算</el-button>
      <el-button
        v-loading="loading"
        v-if="editable"
        class="filter-item"
        size="mini"
        type="danger"
        icon="el-icon-delete"
        @click="doDeleteItem">删除</el-button>
      <el-button
        v-permission="['SYS_ADMIN','COMMON_ADMIN','PURCHASE_POREQ_ALL','PURCHASE_POREQ_CREATE']"
        v-if="supForm.form.busMainData.selfState === '10'"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-tickets"
        @click="toPurchasePoreq">采购申请单</el-button>
      <el-button
        v-permission="['SYS_ADMIN','COMMON_ADMIN','OEM_MO_ALL','OEM_MO_CREATE']"
        v-if="supForm.form.busMainData.selfState === '10'"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-top-right"
        @click="toEmsMo">委外工单</el-button>
      <el-button
        v-permission="['SYS_ADMIN','COMMON_ADMIN','EMS_MO_ALL','EMS_MO_CREATE']"
        v-if="supForm.form.busMainData.selfState === '10'"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-folder-add"
        @click="toOemMo">自制工单</el-button>
      <span class="crud-opts-right">
        <el-tag color="#00ff80">足够库存</el-tag>
        <el-tag color="#ee9900">不够库存</el-tag>
      </span>
    </div>
    <div style="position: relative; width:100%; overflow: auto;">
      <el-table
        :data="mrpDetails"
        :row-class-name="tableRowClassName"
        size="mini"
        style="width:100%;overflow:auto;"
        min-height="200px"
        max-height="600px"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="itemCode" label="物料编号"/>
        <el-table-column label="物料名称" prop="itemName" width="200" show-overflow-tooltip/>
        <el-table-column label="单位" width="90">
          <template slot-scope="scope">
            <template v-for="item in dicts.item_unit">
              <span v-if="scope.row.unit && scope.row.unit === item.dictCode" :key="item.id" >{{ item.dictName }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="MRP计算量" width="120" prop="mrpReqQty" />
        <el-table-column label="所需生产数" width="120" prop="reqQty">
          <template slot-scope="scope">
            <el-input-number v-model.number="scope.row.reqQty" :disabled="!editable" :controls="false" :precision="2" size="mini" style="width: 100%" />
          </template>
        </el-table-column>
        <el-table-column label="物料属性" width="120">
          <template slot-scope="scope">
            <el-select :disabled="!editable" v-model="scope.row.itemType" size="mini" placeholder="物料属性">
              <el-option
                v-for="(item) in dicts.item_type"
                v-if="item.dictCode !== 'virtual'"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="工单/采购部门" width="260">
          <template slot-scope="scope">
            <OrgsetTreeSelect v-model="scope.row.sysOrgCode" :editable="editable && supForm.form.busMainData.funProcess === '10'" :has-priv="false" append-to-body />
          </template>
        </el-table-column>
        <el-table-column label="供应商" width="360">
          <template slot="header">
            供应商<IconHelp display-content="委外生产或采购时,用于自动生成对应的委外工单或采购申请单" />
          </template>
          <template slot-scope="scope">
            <CpyOrgSetSelectDialog
              v-if="scope.row.itemType !== 'prod'"
              v-model="scope.row.otherCpyName"
              :editable="editable && supForm.form.busMainData.funProcess === '10'"
              :cpy-code="scope.row.otherSysOwnerCpy"
              :ori-org-code="scope.row.otherSysOrgCode"
              :param-data="scope.row"
              cpy-owner-type="supply"
              @cpySelectCallback="cpySelectCallback"
              @orgSetSelectCallback="orgSetSelectCallback" />
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="itemSpec" show-overflow-tooltip />
        <el-table-column label="库存数" width="100" prop="stockQty" />
        <el-table-column label="在途数" width="100" prop="processQty">
          <template slot="header">
            在途数<IconHelp display-content="在途数=正在审批交易数+采购订单未入库数+销售订单未出库数" />
          </template>
        </el-table-column>
        <el-table-column label="品牌" prop="itemBrand" show-overflow-tooltip />
        <el-table-column label="备注" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.rmk" :disabled="!editable" size="mini" style="width: 100%"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <poreq-form ref="poreqForm" :sup_this="supForm" />
    <ems-mo-form ref="emsMoForm" :sup_this="supForm" />
    <oem-mo-form ref="oemMoForm" :sup_this="supForm" />
  </div>
</template>

<script>
import mrp from '@/api/prod/Mrp'
import CpyOrgSetSelectDialog from '@/views/components/CpyOrgSetSelectDialog'
import OrgsetTreeSelect from '@/views/components/OrgsetTreeSelect'
import poreqForm from '@/views/purchase/poreq/module/form'
import emsMoForm from '@/views/prod/mo/module/emsForm'
import oemMoForm from '@/views/prod/mo/module/oemForm'

export default {
  dictTypes: ['item_unit', 'item_type'],
  components: { CpyOrgSetSelectDialog, OrgsetTreeSelect, poreqForm, emsMoForm, oemMoForm },
  props: {
    mrpDetails: {
      type: Array,
      required: true
    },
    editable: {
      type: Boolean,
      default: false,
      required: false
    },
    supForm: {
      type: Object,
      default: null,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      selectedDetailRows: [],
      style: 'width: 150px'
    }
  },
  methods: {
    getMaxDetailNum() {
      let detailNum = 0
      this.mrpDetails.forEach(tmprow => {
        if (tmprow.num > detailNum) {
          detailNum = tmprow.num
        }
      })
      return detailNum
    },
    handleSelectionChange(val) {
      this.selectedDetailRows = val
    },
    doDeleteItem() {
      let tmpDetails = JSON.parse(JSON.stringify(this.mrpDetails))
      this.selectedDetailRows.forEach(tmprow => {
        tmpDetails = tmpDetails.filter(vo => vo.num !== tmprow.num)
      })
      this.$emit('setDetails', tmpDetails)
    },
    doCopyItem() {
      const tmpDetails = JSON.parse(JSON.stringify(this.mrpDetails))
      let detailNum = this.getMaxDetailNum()
      this.selectedDetailRows.forEach(tmprow => {
        const addRow = JSON.parse(JSON.stringify(tmprow))
        detailNum++
        addRow.id = null
        addRow.detailLotNo = null
        addRow.num = detailNum
        tmpDetails.push(addRow)
      })
      this.$emit('setDetails', tmpDetails)
    },
    doRunMrp() {
      const _this = this
      if (!_this.supForm.form.busMainData.bomCode) {
        this.$message({
          message: '请选择BOM',
          type: 'warning'
        })
        return
      }
      _this.loading = true
      this.$confirm('确认要运行MRP计算,会覆盖明细?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        mrp.postRequestByName('doRunMrp', _this.supForm.form.busMainData).then(res => {
          _this.loading = false
          _this.$emit('setDetails', res.data)
        }).catch(err => {
          _this.loading = false
          console.log(err)
        })
      }).catch(() => {
        _this.loading = false
      })
    },
    cpySelectCallback(selectedRow, selectObj, curRow) {
      const tmpMrpDetails = JSON.parse(JSON.stringify(this.mrpDetails))
      tmpMrpDetails.forEach(tmprow => {
        if (tmprow.num === curRow.num) {
          tmprow.otherSysOwnerCpy = null
          tmprow.otherCpyName = null
          if (selectedRow) {
            tmprow.otherSysOwnerCpy = selectedRow.cpyCode
            tmprow.otherCpyName = selectedRow.cpyLongName
          }
          return
        }
      })
      this.$emit('setDetails', tmpMrpDetails)
      selectObj.cancel()
    },
    orgSetSelectCallback(orgCode, curRow) {
      const tmpMrpDetails = JSON.parse(JSON.stringify(this.mrpDetails))
      tmpMrpDetails.forEach(tmprow => {
        if (tmprow.num === curRow.num) {
          tmprow.otherSysOrgCode = null
          if (orgCode) {
            curRow.otherSysOrgCode = orgCode
          }
          return
        }
      })
      this.$emit('setDetails', tmpMrpDetails)
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.stockQty > row.reqQty) {
        return 'success-row'
      }
      return 'warning-row'
    },
    toPurchasePoreq() {
      const _this = this
      const busRelList = []
      let cpyKey = null
      let cpyDiffFlag = false
      const busMainData = this.supForm.form.busMainData
      _this.selectedDetailRows.forEach(row => {
        if (row.itemType === 'pur') {
          if (cpyKey && cpyKey !== (row.otherSysOwnerCpy + row.sysOrgCode)) {
            cpyDiffFlag = true
            return
          }
          cpyKey = row.otherSysOwnerCpy + row.sysOrgCode
          busRelList.push({ fromNum: row.num, fromDetailLotNo: row.detailLotNo, fromBusModule: busMainData.busModule, fromBusClass: busMainData.busClass, fromCode: busMainData.sysGenCode, fromId: busMainData.id })
        }
      })
      if (cpyDiffFlag) {
        this.$message({
          message: '请选择相同部门与供应商',
          type: 'warning'
        })
        return
      }
      if (busRelList.length === 0) {
        this.$message({
          message: '请选择属性为采购的记录',
          type: 'warning'
        })
        return
      }
      const _thisform = this.$refs.poreqForm
      _thisform.initDataOfBefore()
      _thisform.addDataFromMrp(busRelList)
    },
    toEmsMo() {
      // 外发工单
      const _this = this
      const busRelList = []
      const busMainData = this.supForm.form.busMainData
      _this.selectedDetailRows.forEach(row => {
        if (row.itemType === 'wf') {
          busRelList.push({ fromNum: row.num, fromDetailLotNo: row.detailLotNo, fromBusModule: busMainData.busModule, fromBusClass: busMainData.busClass, fromCode: busMainData.sysGenCode, fromId: busMainData.id })
        }
      })
      if (busRelList.length !== 1) {
        this.$message({
          message: '请选择一条属性为外发的记录',
          type: 'warning'
        })
        return
      }
      const _thisform = this.$refs.emsMoForm
      _thisform.initDataOfBefore()
      _thisform.addDataFromMrp(busRelList)
    },
    toOemMo() {
      // 自制工单
      const _this = this
      const busRelList = []
      const busMainData = this.supForm.form.busMainData
      _this.selectedDetailRows.forEach(row => {
        if (row.itemType === 'prod') {
          busRelList.push({ fromNum: row.num, fromDetailLotNo: row.detailLotNo, fromBusModule: busMainData.busModule, fromBusClass: busMainData.busClass, fromCode: busMainData.sysGenCode, fromId: busMainData.id })
        }
      })
      if (busRelList.length !== 1) {
        this.$message({
          message: '请选择一条属性为自制的记录',
          type: 'warning'
        })
        return
      }
      const _thisform = this.$refs.oemMoForm
      _thisform.initDataOfBefore()
      _thisform.addDataFromMrp(busRelList)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .el-table {
    ::v-deep {
      /*.cell {
        overflow: visible;
      }
      .el-table__body-wrapper {
        overflow: visible;
      }*/
      .success-row {
        background: #00ff80;
      }
      .warning-row {
        background: #ee9900;
      }
    }
  }
  .el-tabs {
    ::v-deep {
      .el-tabs__content {
        overflow: visible;
      }
    }
  }
</style>
